package com.traffic.between.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.EncrpytionUtil;

import net.sf.json.JSONObject;

@SuppressWarnings("deprecation")
public class LiuliangServiceImpl {
	private static Logger LOG = Logger.getLogger(LiuliangServiceImpl.class);
	public static LiuliangServiceImpl service = new LiuliangServiceImpl();

	private static final String LIULIANG_URL = BetweenProperties.LIULIANG_URL;
	private static final String LIULIANG_KEY = BetweenProperties.LIULIANG_KEY;
	private static final String LIULIANG_CLIENTCODE = BetweenProperties.LIULIANG_CLIENTCODE;

	@SuppressWarnings("resource")
	public String order(String clientOrderNo, String productCode, String phone, String notifyUrl) throws Exception {

		String path = LIULIANG_URL;

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("clientOrderNo", clientOrderNo);
		paramMap.put("productCode", productCode);
		paramMap.put("clientCode", LIULIANG_CLIENTCODE);
		paramMap.put("phone", phone);
		paramMap.put("notifyUrl", notifyUrl);

		StringBuffer buf = new StringBuffer();
		buf.append("clientCode=").append(LIULIANG_CLIENTCODE);
		buf.append("clientOrderNo=").append(clientOrderNo);
		buf.append("phone=").append(phone);
		buf.append("productCode=").append(productCode);
		buf.append("notifyUrl=").append(notifyUrl);
		buf.append(LIULIANG_KEY);
		String sign = EncrpytionUtil.str2MD5(buf.toString());

		paramMap.put("sign", sign);

		String resultStr = "";
		JSONObject json = JSONObject.fromObject(paramMap);
		LOG.info("流量服务接口请求json: " + json);

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(path);
		try {
			if (null != json) {
				StringEntity entity = new StringEntity(json.toString(), "utf-8");
				entity.setContentEncoding("utf-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
				method.setHeader("Connection", "close");
			}
			HttpResponse result = httpClient.execute(method);

			if (result.getStatusLine().getStatusCode() == 200)
				try {
					resultStr = EntityUtils.toString(result.getEntity(), "utf-8");
					LOG.info("流量服务接口的响应数据是: " + resultStr);
				} catch (Exception e) {
					e.printStackTrace();
				}
			else
				resultStr = "{\"resultCode\": \"11111\",\"msg\":\"订购时发生异常,请稍后再试.\"}";
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (method != null) {
				method.releaseConnection();
				method = null;
			}
		}
		return resultStr;
	}
}